//
//  HMStatusModel.m
//  OC新浪微博
//
//  Created by wyman on 16/4/13.
//  Copyright © 2016年 wyman. All rights reserved.
//

#import "HMStatusModel.h"
#import "HMNetworkTool.h"
#import "HMUserAccountModel.h"
#import "HMUserAccount.h"
#import "HMStatu.h"
#import <UIImageView+WebCache.h>
@implementation HMStatusModel
+(HMStatusModel *)sharedInstance
{

    return [[self alloc]init];

}

static HMStatusModel *_instance;


+ (id)allocWithZone:(struct _NSZone *)zone
{
    //    return nil;
    // 懒加载，不能保证多线程并发的实例化是唯一的
    // 加互斥锁，性能非常糟糕。苹果强烈不建议程序员使用！
    //    @synchronized(self) {
    //        if (_instance == nil) {
    //            _instance = [super allocWithZone:zone];
    //        }
    //    }
    // dispatch_once能够确保块代码中的操作只被执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // block中的代码只能被执行一次
        _instance = [super allocWithZone:zone];
        
    });
    return _instance;
}

-(instancetype)init{
    if (self = [super init]) {
//        self.userAccount = [self loadUserAccount];
    }
    return _instance;
}

//加载微博数据

-(void)loadStatuswithblock:(void(^)(NSArray *status,NSError *error))statublock{

//获取微博数据
   
    HMUserAccount *userAccount = [HMUserAccountModel sharedInstance].userAccount;
    
    NSDictionary *paranm = @{
                             @"access_token" : userAccount.access_token,
                             
                             };
    
//    https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00r48sYCx37yBDcd2cba8b450VXC3e
    
    [[HMNetworkTool sharedInstance]GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:paranm progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        //保存属性信息
//        NSString *key = responseObject.keyEnumerator.nextObject;
        NSArray *array = responseObject[@"statuses"];
        
       NSMutableArray *arr = [NSMutableArray array];
        for ( NSDictionary *dict in array) {
            HMStatu *statu = [HMStatu statuWithDict:dict];
            
            [arr addObject:statu];
        }
        
        //缓存出来一张图片
        [self setImage:arr withblock:statublock];
        
//        statublock(arr,nil);
        
//      statublock()
        
        //保存到沙盒
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        statublock(nil,error);
    }];
}

//缓存单行图片
-(void)setImage:(NSArray *)status withblock:(void(^)(NSArray *status,NSError *error))statublock{

    //创建一个队列
        dispatch_group_t group = dispatch_group_create(); // 队列组
    //先遍历这个数组
    for (HMStatu *statu in status) {
        
        NSMutableArray *storPictures = [NSMutableArray array];
        
        storPictures = statu.storePictureURLs;
        
      if (statu.storePictureURLs == nil) {
      
          storPictures = statu.retweeted_status.storePictureURLs;
          
      }
      
        
        if (storPictures.count == 1) {
         
            //拿到这张图片下载
            dispatch_group_enter(group)  ;     // 异步执行操作1
                // longTime1
          
            NSURL *url = storPictures.firstObject;
            
            //通过地址下载这张图片
            [[SDWebImageManager sharedManager] downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                //这里回调
                dispatch_group_leave(group);
            }];
            
            
        }
        
        
    }

 
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        statublock(status,nil);

    });
}



@end
